const express = require('express')
const WebSocket = require('ws')
const cors = require('cors')

const app = express()
const wss = new WebSocket.Server({ port: 5567 })

// 存储所有连接的客户端
const clients = new Set()
// 设备状态
const deviceStatus = {
  lightStatus: false,
  temperature: 25 // 默认温度
}

// 启用 CORS
app.use(cors())
app.use(express.json())

// WebSocket 连接处理
wss.on('connection', (ws) => {
  clients.add(ws)
  
  // 发送当前状态
  ws.send(JSON.stringify({ 
    type: 'status',
    lightStatus: deviceStatus.lightStatus,
    temperature: deviceStatus.temperature
  }))

  ws.on('close', () => {
    clients.delete(ws)
  })
})

// 广播消息给所有客户端
function broadcast(message) {
  clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify(message))
    }
  })
}

// 开灯接口
app.post('/open', (req, res) => {
  deviceStatus.lightStatus = true
  broadcast({ type: 'light', status: deviceStatus.lightStatus })
  res.json({ success: true, status: deviceStatus.lightStatus })
})

// 关灯接口
app.post('/close', (req, res) => {
  deviceStatus.lightStatus = false
  broadcast({ type: 'light', status: deviceStatus.lightStatus })
  res.json({ success: true, status: deviceStatus.lightStatus })
})

// 设置温度接口
app.post('/setT/:temperature', (req, res) => {
  const temp = parseFloat(req.params.temperature)
  if (isNaN(temp)) {
    return res.status(400).json({ error: '无效的温度值' })
  }
  deviceStatus.temperature = temp
  broadcast({ type: 'temperature', value: temp })
  res.json({ success: true, temperature: temp })
})

// 获取状态接口
app.get('/status', (req, res) => {
  res.json(deviceStatus)
})

app.listen(5566, () => {
  console.log('HTTP Server running on port 5566')
  console.log('WebSocket Server running on port 5567')
}) 